<?php
/***
 * Candy 短信发送
 *
 * $Author: 刘森 (fingerboy@qq.com) $
 * $Date: 2020-01-23 18:50:08 $
 */
 
declare(strict_types=1);
namespace Candy\Extend;

defined('CANDY') OR die('You Are A Bad Guy. o_O???');

class Sms {
	/**
	 * 阿里云云通信接口特殊编码
	 */
	private static function aliYunEncode(string $waitEncode): string
	{
		$tempEncode = urlencode($waitEncode);
		$tempEncode = str_replace('+','%20',$tempEncode);
		$tempEncode = str_replace('*','%2A',$tempEncode);
		$tempEncode = str_replace('%7E','~',$tempEncode);
		return $tempEncode;
	}
	
	/**
	 * 阿里云云通信接口
	 */
	public static function aliYun(array $data = []): bool
	{
		$phoneNumber = null;
		$tempTimestamp = gmdate('Y-m-d\TH:i:s\Z');
		is_array($data['number']) OR $data['number'] = [$data['number']];
		foreach ($data['number'] as $val) {
			$phoneNumber .= $val.',';
		}
		$recNum = substr($phoneNumber,0,-1);
		if(is_null(G('sms'))) Tpl::report(__FILE__,__LINE__,'Error#M.7');
		$sms = G('sms');
		
		$getData = [
				'AccessKeyId'=>$sms['aliYunAccessKeyID'],
				'Timestamp'=>$tempTimestamp,
				'SignatureMethod'=>'HMAC-SHA1',
				'SignatureVersion'=>'1.0',
				'SignatureNonce'=>uniqid(mt_rand(0,0xffff), true),
				'Format'=>'JSON',
				'Action'=>'SendSms',
				'Version'=>'2017-05-25',
				'RegionId'=>$sms['aliYunRegionId'],
				'PhoneNumbers'=>$recNum,
				'SignName'=>$sms['aliYunSignName'],
				'TemplateCode'=>$data['templateCode']
			];
		if(!empty($data['param'])){
			$getData['TemplateParam'] = json_encode($data['param']);
		}
		ksort($getData);
		$sortString = null;
		foreach ($getData as $key => $val) {
			$sortString .= self::aliYunEncode($key) .'='. self::aliYunEncode($val) .'&';
		}
		$sortString = substr($sortString,0,-1);
		$signed = base64_encode(hash_hmac('sha1','GET&%2F&' . self::aliYunEncode($sortString), $sms['aliYunAccessKeySecret']."&", true));
		$signData = ['Signature'=>$signed];
		$getData=array_merge($getData, $signData);

		$info = Http::post('http://dysmsapi.aliyuncs.com/', $getData, ['header'=>'x-sdk-client: php/2.0.0']);
		$info = json_decode($info);
		$info = $info->Code;
		if($info == 'OK'){
			return true;
		}else{
			return false;
		}
	}
}
